package cn.edu.xmist.supermarket.wtlvgcl.controller;

import cn.edu.xmist.supermarket.wtlvgcl.config.Vars;
import cn.edu.xmist.supermarket.wtlvgcl.entity.XitongPO;
import cn.edu.xmist.supermarket.wtlvgcl.entity.ChanpinPO;
import cn.edu.xmist.supermarket.wtlvgcl.service.XitongService;
import cn.edu.xmist.supermarket.wtlvgcl.service.ChanpinService;
import cn.edu.xmist.supermarket.wtlvgcl.util.ObjtoLayJson;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/xitong")
public class XitongController {

  public static final String[] COLUMNS = {"id", "houseCode", "houseName"};

  @Autowired private XitongService xitongService;
  @Autowired private ChanpinService wareService;

  @RequestMapping("/list")
  public String list(Integer page, Integer limit) throws Exception {
    List<XitongPO> list = xitongService.list();

    return ObjtoLayJson.ListtoJson(list, COLUMNS);
  }

  @RequestMapping("/saveOrUpdate")
  public String saveOrUpdate(XitongPO house) {
    if (house.getId() == null) {
      QueryWrapper<XitongPO> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("house_code", house.getHouseCode());
      List<XitongPO> list = xitongService.list(queryWrapper);
      if (list.size() > 0) {
        return Vars.FAILURE;
      }
    }
    Boolean flag = xitongService.saveOrUpdate(house);
    return Vars.SUCCESS;
  }

  @RequestMapping("/deleteById")
  public String deleteById(Long id) {
    XitongPO house = xitongService.getById(id);
    QueryWrapper<ChanpinPO> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("house_code", house.getHouseCode());
    List<ChanpinPO> list = wareService.list(queryWrapper);
    if (list.size() > 0) {
      return Vars.FAILURE;
    }
    Boolean flag = xitongService.removeById(id);
    return Vars.SUCCESS;
  }
}
